package com.lefu.es.system;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lefu.es.application.IwellnessApplication;
import com.lefu.es.blenew.bean.BluetoothLeDevice1;
import com.lefu.es.blenew.constant.BluetoolUtil1;
import com.lefu.es.blenew.service.BluetoothLeScannerInterface;
import com.lefu.es.blenew.service.BluetoothLeService;
import com.lefu.es.blenew.service.BluetoothUtils1;
import com.lefu.es.blenew.utils.StringUtils1;
import com.lefu.es.cache.CacheHelper;
import com.lefu.es.constant.AppData;
import com.lefu.es.constant.BLEConstant;
import com.lefu.es.constant.BluetoolUtil;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.db.RecordDao;
import com.lefu.es.db2.MacDao;
import com.lefu.es.entity.Device;
import com.lefu.es.entity.DeviceMacDao;
import com.lefu.es.entity.NutrientBo;
import com.lefu.es.entity.Records;
import com.lefu.es.service.RecordService;
import com.lefu.es.service.TimeService;
import com.lefu.es.service.UserService;
import com.lefu.es.util.LogUtil;
import com.lefu.es.util.MyUtil;
import com.lefu.es.util.SharedPreferencesUtil;
import com.wellness.scale.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/6.
 * 蓝牙基础界面
 */
public abstract class BaseBleActivity extends AppCompatActivity {


    public static final int REQUEST_CODE_LOCATION_SETTINGS = 2;
    protected static final int REQUEST_ACCESS_COARSE_LOCATION_PERMISSION = 101;
    public BluetoothUtils1 mBluetoothUtils;
    public BluetoothLeScannerInterface mScanner;
    public BluetoothLeService mBluetoothLeService;
    public String mDeviceAddress;
    public String mDeviceName;
    public boolean mConnected = false;
    public boolean mActivty = true; //页面是否激活
    public RecordService recordService;

    protected Handler scanHandler = new Handler();
    protected Runnable scanThread = new Runnable() {

        public void run() {
            startScan();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                // LogUtil.d( "系统大于5.0以上");
                //scanHandler.postDelayed(scanThread, -1);
            } else {
                // LogUtil.d( "系统小于5.0");
                scanHandler.postDelayed(scanThread, 300);
            }
        }
    };

    protected SoundPool soundpool;
    protected Records receiveRecod = null;
    protected boolean ageError = false;
    protected BluetoothAdapter mBtAdapter;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UtilConstants.scaleChangeMessage:
                    /*保存秤类型*/
                    if (UtilConstants.su == null) {
                        UtilConstants.su = new SharedPreferencesUtil(LoadingActivity.mainActivty);
                    }
                    UtilConstants.su.editSharedPreferences("lefuconfig", "scale", UtilConstants.CURRENT_SCALE);
                    /*保存用户信息*/
                    try {
                        UserService uservice = new UserService(BaseBleActivity.this);
                        uservice.update(UtilConstants.CURRENT_USER);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 0:
                    Records data = (Records) msg.obj;
                    if (null != data && data.getReceiveMsg().length() == 22) {
                        saveData(data);
                    }
                    break;
                case 3:
                    Records data1 = (Records) msg.obj;
                    if (null != data1 && data1.getReceiveMsg() != null && data1.getReceiveMsg().length() == 22) {
                        saveData(data1);
                    }
                    break;
                default:
            }
        }
    };

    private List<DeviceMacDao> deviceMacs;
    protected final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                LogUtil.e("Unable to initialize Bluetooth");
                finish();
            }
            LogUtil.e( "开始连接蓝牙.......");
            if (!deviceMacs.isEmpty()) {
                for (int i = 0; i < deviceMacs.size(); i++) {
                    if (deviceMacs.get(i).getMac().equals(mDeviceAddress)) {
                        LogUtil.e( "=====有绑定过的mac开始连接:" + deviceMacs.get(i).getMac());
                        mBluetoothLeService.disconnect();
                        notifyHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mBluetoothLeService.connect(mDeviceAddress);
                            }
                        }, 100);
                        break;
                    } else {
                        LogUtil.e( "===========没有绑定mac开始连接:" + mDeviceAddress);
                        if (!TextUtils.isEmpty(mDeviceAddress)) {
                            if (isAutoActivity()) {
                                mBluetoothLeService.disconnect();
                                notifyHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mBluetoothLeService.connect(mDeviceAddress);
                                    }
                                }, 100);
                                break;
                            }
                        }
                    }
                }
            } else {
                LogUtil.d( "===========没有绑定mac开始连接:" + mDeviceAddress);
                if (!TextUtils.isEmpty(mDeviceAddress)) {
                    if (isAutoActivity()) {
                        mBluetoothLeService.disconnect();
                        notifyHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mBluetoothLeService.connect(mDeviceAddress);
                            }
                        }, 100);
                    }
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private AlertDialog.Builder builder = null;
    private BluetoothLeDevice1 deviceLe;
    private Handler notifyHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
               case BluetoolUtil1.FOUND_DEVICE:
                   connectDevice(msg);
                    break;
                case BluetoolUtil1.RECEIVE_DATA: //接收到数据
                    Device data = (Device) msg.obj;
                    LogUtil.d("*****接收到数据**data-->" + data);
                    String curActivityName = getRunningActivityName();
                    LogUtil.d( "当前显示的activity名称是：" + curActivityName);
                    if (curActivityName.contains("BodyFatNewActivity") ||
                            curActivityName.contains("BodyScaleNewActivity") ||
                            curActivityName.contains("KitchenScaleActivity") ||
                            curActivityName.contains("KitchenScaleActivity1") ||
                            curActivityName.contains("BabyScaleActivity") ||
                            curActivityName.contains("KitchenScaleActivity1") ||
                            curActivityName.contains("BabyScaleNewActivity")) {
                        /*if (!deviceMacs.isEmpty()) {
                            for (int i = 0; i < deviceMacs.size(); i++) {
                                if (!TextUtils.isEmpty(deviceMacs.get(i).getMac())) {
                                    receiveBleData(data.getDeviceData(), data.getMac(), data.getDeviceName());
                                    break;
                                }
                            }
                        }*/
                        if (!TextUtils.isEmpty(mDeviceAddress)) {
                            boolean isBind = StringUtils1.isBindDevice(mDeviceAddress);
                            if (isBind){
                                receiveBleData(data.getDeviceData(), data.getMac(), data.getDeviceName());
                            }
                        }
                    } else if (curActivityName.contains("AutoBLEActivity")) {
                        receiveBleData(data.getDeviceData(), data.getMac(), data.getDeviceName());
                    }
                    break;
                case BluetoolUtil1.DESCIVE_SERVICE:
                    BluetoothLeDevice1 deviceLe1 = (BluetoothLeDevice1) msg.obj;
                    if (deviceLe1 != null) {
                        mDeviceName = deviceLe1.getName();
                    }
                    discoverBleService();
                    break;
                case BluetoolUtil1.DESCIVE_DISCONNECT: //蓝牙断开
                    updateConnectionState(R.string.disconnected);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //scanHandler.removeCallbacks(scanThread);
                    }
                    //startScan();
                    scanHandler.post(scanThread);
                    break;
                case BluetoolUtil1.DESCIVE_CONNECTED: //蓝牙连接
                    LogUtil.e("****蓝牙已连接连接****mDeviceAddress-->" + mDeviceAddress);
                    //scanHandler.removeCallbacks(scanThread);
                    mScanner.stopScan();
                    updateConnectionState(R.string.connected);
                    break;
                case BluetoolUtil1.GUANGBO_DATA:
                    BluetoothLeDevice1 deviceLe2 = (BluetoothLeDevice1) msg.obj;
                    String receiveStr = deviceLe2.getmRevicerData();
                    if (StringUtils1.isScaleData(receiveStr)) {
                        LogUtil.e("***GUANGBO_DATA有效的广播数据-->" + receiveStr + " mDeviceName:" + mDeviceName
                        +"***是不是雷达界面-->" + isAutoActivity());
                        deviceMacs = StringUtils1.getBindDeviceMac();
                        if (deviceMacs.size() > 0) {
                            if (isAutoActivity()) {
                                for (int i = 0; i < deviceMacs.size(); i++) {
                                    if (!TextUtils.isEmpty(deviceMacs.get(i).getMac())) {
                                        receiveBleData(receiveStr, deviceLe2.getAddress(), deviceLe2.getName());
                                    }
                                }
                            }else{
                                boolean isBind = StringUtils1.isBindDevice(deviceLe2.getAddress());
                                if (isBind) {
                                    receiveBleData(receiveStr, deviceLe2.getAddress(), deviceLe2.getName());
                                }
                            }
                        } else {
                            if (isAutoActivity()) {
                                receiveBleData(receiveStr, deviceLe2.getAddress(), deviceLe2.getName());
                            }
                        }
                    }
                    break;
                default:
            }
        }
    };

    private void connectDevice(Message msg) {
        LogUtil.e("****发现通知，准备连接***mDeviceAddress*"+mDeviceAddress);
        LogUtil.e("****FOUND_DEVICE---[蓝牙连接状态]==" + (null == mBluetoothLeService ?
                "未初始化" : mBluetoothLeService.getConnectionState())
        +"***mDeviceAddress-->"+mDeviceAddress);
        deviceLe = (BluetoothLeDevice1) msg.obj;
        LogUtil.e("*****deviceLe-->"+deviceLe);
        if ((null != deviceLe && null != mBluetoothLeService &&
                mBluetoothLeService.getConnectionState()==BluetoothLeService.STATE_DISCONNECTED)) {
            mDeviceAddress = deviceLe.getAddress();
            mDeviceName = deviceLe.getName();
            boolean isBind = StringUtils1.isBindDevice(mDeviceAddress);
            LogUtil.e("*****mDeviceAddress-->"+mDeviceAddress
                    +"***mDeviceName-->"+mDeviceName+"***isBind-->"+isBind);
            if (isBind) {
                if (!TextUtils.isEmpty(mDeviceAddress)) {
                    LogUtil.e("*****有绑定过的mac开始连接***mDeviceAddress-->" + mDeviceAddress);
                    mBluetoothLeService.disconnect();
                    notifyHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mScanner.stopScan();
                            mBluetoothLeService.connect(mDeviceAddress);
                        }
                    }, 100);
                }
            } else {
                LogUtil.e("****没有绑定mac开始连接***mDeviceAddress-->" + mDeviceAddress
                        +"***isAutoActivity()-->"+isAutoActivity());
                if (!TextUtils.isEmpty(mDeviceAddress)) {
                    if (isAutoActivity()) {
                        LogUtil.e("*****开始连接****");
                        mBluetoothLeService.disconnect();
                        notifyHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mScanner.stopScan();
                                mBluetoothLeService.connect(mDeviceAddress);
                            }
                        }, 100);
                    }else{
                        scanHandler.post(scanThread);
                    }
                }
            }

            /*  if (!deviceMacs.isEmpty()) {
                for (int i = 0; i < deviceMacs.size(); i++) {
                    if (deviceMacs.get(i).getMac().equals(mDeviceAddress)) {
                        LogUtil.e("****有绑定过的mac开始连接-->" + deviceMacs.get(i).getMac());
                        mScanner.stopScan();
                        //scanHandler.removeCallbacks(scanThread);
                        mBluetoothLeService.connect(mDeviceAddress);
                        break;
                    } else {
                        if (!TextUtils.isEmpty(mDeviceAddress)) {
                            if (isAutoActivity()) {
                                LogUtil.e("****没有绑定mac开始连接-->" + mDeviceAddress);
                                mScanner.stopScan();
                                //scanHandler.removeCallbacks(scanThread);
                                mBluetoothLeService.connect(mDeviceAddress);
                                break;
                            }
                        }
                    }
                }
            } else {
                LogUtil.e( "*****没有绑定mac开始连接-->" + mDeviceAddress);
                if (!TextUtils.isEmpty(mDeviceAddress)) {
                    if (isAutoActivity()) {
                        mScanner.stopScan();
                        //scanHandler.removeCallbacks(scanThread);
                        mBluetoothLeService.connect(mDeviceAddress);
                    }
                }
            }*/

        }else {
            LogUtil.e("***重新扫描***");
            scanHandler.post(scanThread);
        }
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message msg1 = null;
            switch (intent.getAction()) {
                case BLEConstant.ACTION_GATT_CONNECTED:
                    mConnected = true;
                    msg1 = notifyHandler.obtainMessage(BluetoolUtil1.DESCIVE_CONNECTED);
                    break;
                case BLEConstant.ACTION_GATT_DISCONNECTED:
                    mConnected = false;
                    msg1 = notifyHandler.obtainMessage(BluetoolUtil1.DESCIVE_DISCONNECT);
                    break;
                case BLEConstant.ACTION_GATT_SERVICES_DISCOVERED:
                    LogUtil.e( "发现服务：" + mActivty + ":mBluetoothLeService:" + mBluetoothLeService);
                    if (null != mBluetoothLeService && mActivty) {
                        LogUtil.e( "发送消息:");
                        msg1 = notifyHandler.obtainMessage(BluetoolUtil1.DESCIVE_SERVICE);
                    }
                    break;
                case BLEConstant.ACTION_DATA_AVAILABLE:
                    String readMessage = intent.getStringExtra(BLEConstant.EXTRA_DATA);
                    String mac = intent.getStringExtra("mac");
                    LogUtil.e("****接收数据-->" + readMessage);
                    if (!TextUtils.isEmpty(readMessage) && readMessage.length() > 10) {
                        LogUtil.d("***receiveBleData1检测读取到数据-->" + readMessage);
                        msg1 = notifyHandler.obtainMessage(BluetoolUtil1.RECEIVE_DATA);
                        Device device = new Device();
                        device.setDeviceData(readMessage);
                        device.setMac(mac);
                        device.setDeviceName(mDeviceName);
                        msg1.obj = device;
                    }
                    break;
                default:
            }
            if (msg1 != null) {
                notifyHandler.sendMessage(msg1);
            }
        }
    };


    /*** 蓝牙扫描线程 **/
    private Runnable ScanRunnable = new Runnable() {
        public void run() {
            startDiscovery();
        }
    };
    private AlertDialog mAlertDialog;
    //final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    /*** 检测是否有测量记录线程 ***/
    private Runnable CheckHasDataRunnable = new Runnable() {
        public void run() {
            if (!AppData.hasCheckData && mActivty && !UtilConstants.isTipChangeScale) {
                scaleChangeAlert();
                UtilConstants.isTipChangeScale = true;
            }
        }
    };

    /**
     * Location service if enable
     *
     * @param context
     * @return location is enable if return true, otherwise disable.
     */
    public static final boolean isLocationEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean networkProvider = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean gpsProvider = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        LogUtil.d( "networkProvider:" + networkProvider);
        LogUtil.d( "gpsProvider:" + gpsProvider);
        if (networkProvider && gpsProvider) return true;
        return false;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室 外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param
     */
    public static final void openGPS(Context context) {
        LogUtil.d( "强制帮用户打开GPS");
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    private void insertDummyContactWrapper() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
            permissionsNeeded.add("Location");
        if (!addPermission(permissionsList, Manifest.permission.CAMERA))
            permissionsNeeded.add("CAMERA");
        if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
            permissionsNeeded.add("Read Contacts");
        if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
            permissionsNeeded.add("Write Contacts");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // Need Rationale
                //  String message = "You need to grant access to " + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    //    message = message + ", " + permissionsNeeded.get(i);

            /*    showAlertDialog(getString(R.string.permission_title_rationale), message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {*//*
                    requestPermissions(new String[]{
                                    Manifest.permission.ACCESS_COARSE_LOCATION,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.READ_EXTERNAL_STORAGE},
                            REQUEST_ACCESS_COARSE_LOCATION_PERMISSION);
                      /*      }
                        }, getString(R.string.ok_btn), null, getString(R.string.cancle_btn));
*/
               /* showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });*/
                    return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_ACCESS_COARSE_LOCATION_PERMISSION);
            return;
        }

        // insertDummyContact();
    }

    private boolean addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recordService = new RecordService(this);
        mBluetoothUtils = new BluetoothUtils1(this);
        if (mBluetoothUtils.isBluetoothLeSupported()) {
            BluetoolUtil.bleflag = true;
            //初始化蓝牙相关对象
            //scanHandler = new Handler();
            mScanner = mBluetoothUtils.initBleScanner(notifyHandler);
            //注册通知
            registerReceiver(mGattUpdateReceiver, BluetoothUtils1.makeGattUpdateIntentFilter());
            //绑定蓝牙服务服务
            final Intent gattServiceIntent = new Intent(BaseBleActivity.this, BluetoothLeService.class);
            bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //申请权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    LogUtil.i( "================检查权限=============");
                    requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                            getString(R.string.permission_blurtooth),
                            REQUEST_ACCESS_COARSE_LOCATION_PERMISSION);
                } else {
                    //启动扫描
                    scanHandler.post(scanThread);
                }
            } else {
                scanHandler.post(scanThread);
            }
        } else {
            //BT
            BluetoolUtil.bleflag = false;
        }
    }

    /**
     * 请求权限
     * <p>
     * 如果权限被拒绝过，则提示用户需要权限
     */
    protected void requestPermission(final String permission, String rationale, final int requestCode) {
        LogUtil.d( "如果权限被拒绝过，则提示用户需要权限");
        if (shouldShowRequestPermissionRationale(permission)) {
            showAlertDialog(
                    getString(R.string.permission_title_rationale),
                    rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            LogUtil.d( "=================点了确定");
                            requestPermissions(new String[]{permission}, requestCode);
                        }
                    }, getString(R.string.ok_btn)

            );


        } else {
            requestPermissions(new String[]{permission}, requestCode);
        }
    }

    /**
     * 显示指定标题和信息的对话框
     *
     * @param title                         - 标题
     * @param message                       - 信息
     * @param onPositiveButtonClickListener - 肯定按钮监听
     * @param positiveText                  - 肯定按钮信息
     */
    protected void showAlertDialog(String title,
                                   String message,
                                   DialogInterface.OnClickListener onPositiveButtonClickListener,
                                   String positiveText
    ) {
        builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setCancelable(false);
        mAlertDialog = builder.show();

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mActivty = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.e("**onDestroy***");
        scanHandler.removeCallbacks(scanThread);
        try {
            unbindService(mServiceConnection);
            mBluetoothLeService = null;
            unregisterReceiver(mGattUpdateReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始扫描蓝牙
     */
    protected void startScan() {
        LogUtil.e("****startScan****");
        final boolean mIsBluetoothOn = mBluetoothUtils.isBluetoothOn();
        final boolean mIsBluetoothLePresent = mBluetoothUtils.isBluetoothLeSupported();
        if (mIsBluetoothOn && mIsBluetoothLePresent && mActivty) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                mScanner.scanLeDevice(-1, true);
            } else {
                mScanner.scanLeDevice(300, true);
            }
        } else {
            if (IwellnessApplication.isShowFag == 1) {
            } else {
                mBluetoothUtils.askUserToEnableBluetoothIfNeeded();
                IwellnessApplication.isShowFag = 1;
            }
        }
    }

    protected void stopScan(){
        if (mScanner!=null){
            mScanner.stopScan();
        }
    }

    protected void disConnect(){
        LogUtil.e("****断开连接****");
        if (mBluetoothLeService!=null){
            mBluetoothLeService.disconnect();
        }
    }

    /**
     * 更新界面蓝牙标志
     *
     * @param resourceId
     */
    public abstract void updateConnectionState(final int resourceId);

    /**
     * 发现蓝牙服务
     */
    public abstract void discoverBleService();

    /**
     * 接收到蓝牙数据
     */
    public abstract void receiveBleData(String readMessage, String mac, String deviceName);

    /**
     * 播放声音
     */
    public void playSound() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                soundpool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
                int sourceid = -1;
                sourceid = soundpool.load(BaseBleActivity.this, R.raw.ring, 0);
                AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
                soundpool.play(sourceid, streamVolume, streamVolume, 1, 0, 1F);
            }
        }).start();
    }

    /**
     * 将数据ArrayList中
     *
     * @return
     */
    protected ArrayList<Baby> getData() {
        ArrayList<Baby> items = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Baby baby = new Baby();
            baby.setName("baby" + i);
            items.add(baby);
        }
        return items;
    }

    protected void showAlertDialog(String title) {
        new com.lefu.es.view.AlertDialog(BaseBleActivity.this)
                .builder().setTitle(getResources().getString(R.string.waring_title)).setMsg(title)
                .setPositiveButton(getResources().getString(R.string.ok_btn), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null == UtilConstants.su) {
                            UtilConstants.su = new SharedPreferencesUtil(BaseBleActivity.this);
                        }
                        UtilConstants.su.editSharedPreferences("lefuconfig", "first_install_dailog", "1");
                        UtilConstants.FIRST_INSTALL_DAILOG = "1";
                    }
                }).show();
    }

    public void stopBle() {
        try {
            scanHandler.removeCallbacks(scanThread);
            unbindService(mServiceConnection);
            mBluetoothLeService = null;
            unregisterReceiver(mGattUpdateReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始检测蓝牙
     */
    public void startDiscovery() {
        try {
            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            mBtAdapter = BluetoothAdapter.getDefaultAdapter();
            mBtAdapter.startDiscovery();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 停止扫描
     */
    public void stopDiscovery() {
        try {
            mBtAdapter.cancelDiscovery();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 秤改变弹窗
     */
    public void scaleChangeAlert() {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), ScaleChangeAlertActivity.class);
        startActivity(intent);
    }

    /**
     * 停止扫描服务
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public void setLocationService() {
        Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        BaseBleActivity.this.startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        super.onPause();
        /* 秤识别中 */
        AppData.isCheckScale = false;
        mActivty = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.e("****onResume:mBluetoothLeService-->" + mBluetoothLeService);
        /***查询所有据***/
        //deviceMacs = (ArrayList<DeviceMac>) DataSupport.findAll(DeviceMac.class);
        initBle();
    }

    protected void initBle() {
        if (mBluetoothLeService == null) {
            LogUtil.d( "==初始化蓝牙相关对象");
            mBluetoothUtils = new BluetoothUtils1(this);
            if (mBluetoothUtils.isBluetoothLeSupported()) {
                BluetoolUtil.bleflag = true;
                //初始化蓝牙相关对象
                //scanHandler = new Handler();
                mScanner = mBluetoothUtils.initBleScanner(notifyHandler);
                //注册通知
                registerReceiver(mGattUpdateReceiver, BluetoothUtils1.makeGattUpdateIntentFilter());
                final Intent gattServiceIntent = new Intent(BaseBleActivity.this, BluetoothLeService.class);
                boolean isBing = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
                LogUtil.d("****isBing-->" + isBing);
            }
        }
        /* 秤识别中 */
        AppData.isCheckScale = false;
        mActivty = true;
        deviceMacs = MacDao.queryAll();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        LogUtil.d( "===============requestCode:" + requestCode + "");
        switch (requestCode) {
            case REQUEST_ACCESS_COARSE_LOCATION_PERMISSION:
                if (null != grantResults && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (null != mAlertDialog) mAlertDialog.dismiss();
                    //启动扫描
                    LogUtil.d( "启动扫描");
                    scanHandler.post(scanThread);
                } else {
                    startScanBLE();
                }
                break;

            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    protected void startScanBLE() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                    getString(R.string.permission_blurtooth),
                    REQUEST_ACCESS_COARSE_LOCATION_PERMISSION);
        } else {
            LogUtil.e("****启动扫描****");
            scanHandler.post(scanThread);
        }
    }

    public void saveReveiveBleData(String readMessage) {
      /*  if (readMessage != null && readMessage.length() == 40) {
            readMessage = readMessage.substring(0, 22);
            LogUtil.d( "=====sub后的：" + readMessage);
        }*/
        LogUtil.d( "reveiveBleData检测读取到数据:" + readMessage);
        if (TextUtils.isEmpty(readMessage) || readMessage.length() < 10) return;
        //测脂错误
        if (readMessage.equals(UtilConstants.ERROR_CODE)) {
            if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)
                    || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                Toast.makeText(BaseBleActivity.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(BaseBleActivity.this, getString(R.string.user_data_error_lb), Toast.LENGTH_LONG).show();
            }
            return;
        } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
            Toast.makeText(BaseBleActivity.this, getString(R.string.scale_measurement_error), Toast.LENGTH_LONG).show();
            return;
        }
        //秤和人体参数不匹配
        if (!readMessage.toLowerCase().startsWith(UtilConstants.BABY_SCALE)) {
            if (!ageError) {
                if (UtilConstants.CURRENT_USER.getAgeYear() < 10 || UtilConstants.CURRENT_USER.getBheigth() < 100) {
                    if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_KG)) {
                        showAgeOrHeightAlertDailog(getString(R.string.age_error_4));
                    } else {
                        showAgeOrHeightAlertDailog(getString(R.string.age_error_6));
                    }
                    return;
                }
            }
        }


        //处理不同类型的秤
        boolean newScale = false;
        try {
            if ((readMessage.startsWith("0306"))) {//阿里秤
                newScale = true;
                UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            } else {
                newScale = false;
                /** 称类型判断 */
                String choice_scale = "";
                if ((readMessage.toLowerCase().startsWith(UtilConstants.BODY_SCALE))) {
                    choice_scale = UtilConstants.BODY_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BATHROOM_SCALE))) {
                    choice_scale = UtilConstants.BATHROOM_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BABY_SCALE))) {
                    choice_scale = UtilConstants.BABY_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.KITCHEN_SCALE))) {
                    choice_scale = UtilConstants.KITCHEN_SCALE;
                }
                UtilConstants.CURRENT_SCALE = choice_scale;
            }
            LogUtil.d( "mDeviceName:" + mDeviceName);
            if (null != mDeviceName && mDeviceName.toLowerCase().startsWith(UtilConstants.DLscaleName) || (null != mDeviceName && mDeviceName.toLowerCase().startsWith("heal")) && readMessage.length() == "cf9015d6153a353b0000bd".length()) { //新的DL Scale
                //CF 88 13 00 14 00 00 00 00 00 40
                LogUtil.e("readMessage:" + readMessage);
                if (RecordDao.isLockData(readMessage)) {
                    if ((System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                        UtilConstants.receiveDataTime = System.currentTimeMillis();
                        dueDate(readMessage, 3);
                    }
                } else {
                    dueDate(readMessage, 2);
                }
            } else {
                /**判断是不是两次连续的数据*/
                if (readMessage.length() > 31 && !mDeviceName.toLowerCase().startsWith(UtilConstants.DLscaleName) && (System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    if (newScale) {
                            /*脂肪秤*/
                        UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
                        UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                        dueDate(readMessage, 1);
                    } else {
                        if (readMessage.equals(UtilConstants.ERROR_CODE)) {
                            if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)
                                    || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                                Toast.makeText(BaseBleActivity.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(BaseBleActivity.this, getString(R.string.user_data_error_lb), Toast.LENGTH_LONG).show();
                            }
                            return;
                        } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
                            Toast.makeText(BaseBleActivity.this, getString(R.string.scale_measurement_error), Toast.LENGTH_LONG).show();
                            return;
                        }
                            /*显示称类型错误*/
                        if (!readMessage.startsWith(UtilConstants.BODY_SCALE) && readMessage.length() > 31) {
                                /*跳转到制定的秤界面*/
                            if (readMessage.startsWith(UtilConstants.BATHROOM_SCALE)) {
                                    /*脂肪秤*/
                                UtilConstants.CURRENT_SCALE = UtilConstants.BATHROOM_SCALE;
                                UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                                    /*保存测量数据*/
                                RecordDao.dueDate(recordService, readMessage);
                            } else if (readMessage.startsWith(UtilConstants.BABY_SCALE)) {
                                    /*婴儿秤*/
                                UtilConstants.CURRENT_SCALE = UtilConstants.BABY_SCALE;
                                UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                                    /*保存测量数据*/
                                RecordDao.dueDate(recordService, readMessage);
                            } else if (readMessage.startsWith(UtilConstants.KITCHEN_SCALE)) {
                                    /* 厨房秤 */
                                UtilConstants.CURRENT_SCALE = UtilConstants.KITCHEN_SCALE;
                                UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                                    /* 保存测量数据 */
                                RecordDao.dueKitchenDate(recordService, readMessage, null);
                            }
                            handler.sendEmptyMessage(UtilConstants.scaleChangeMessage);

                            return;
                        }
                        if (readMessage.equals(UtilConstants.ERROR_CODE_GETDATE)) {
                            openErrorDialog("2");
                            return;
                        }
                        if ((readMessage.startsWith("c") && readMessage.length() > 31)) {
                            dueDate(readMessage, 0);
                        }
                    }
                }
            }

        } catch (Exception e) {
            LogUtil.e( "解析数据异常" + e.getMessage());
        }
    }

    protected void showAgeOrHeightAlertDailog(String title) {
        new com.lefu.es.view.AlertDialog(BaseBleActivity.this).builder()
                .setTitle(getResources().getString(R.string.ageorheight_error_title)).setMsg(title)
                .setPositiveButton(getResources().getString(R.string.ok_btn), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ageError = false;
                    }
                }).show();
        ageError = true;
    }

    /**
     * 数据处理
     *
     * @param readMessage
     * @param i
     */
    private void dueDate(String readMessage, int i) {
        switch (i) {
            case 0:
                receiveRecod = MyUtil.parseMessage(this.recordService, readMessage);
                break;
            case 1:
                receiveRecod = MyUtil.parseZuKangMeaage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
                break;
            /***新称过程数据***/
            case 2:
                LogUtil.i( readMessage);
                break;
            /***新秤锁定数据***/
            case 3:
                LogUtil.i( "=======新秤锁定数据=======");
                receiveRecod = MyUtil.parseDLScaleMessage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
                Message msg1 = handler.obtainMessage(0);
                msg1.obj = receiveRecod;
                handler.sendMessage(msg1);
                break;
            default:
        }
        if (i != 2) {
            if (receiveRecod != null) {
                receiveRecod.setReceiveMsg(readMessage);
                if (deviceMacs.isEmpty()) {
                    for (int sun = 0; sun <= deviceMacs.size(); sun++) {
                        LogUtil.d( "当前没有绑定mac");
                        if ("cf".equals(receiveRecod.getScaleType())) {
                            bindScale("2");
                        } else if ("ce".equals(receiveRecod.getScaleType())) {
                            bindScale("1");
                        } else if ("ca".equals(receiveRecod.getScaleType())) {
                            bindScale("3");
                        } else {
                            bindScale("4");
                        }
                    }
                } else {
                    for (int sun = 0; sun < deviceMacs.size(); sun++) {
                        if (!TextUtils.isEmpty(deviceMacs.get(sun).getMac())) {
                            //LogUtil.d( "当前没有绑定mac");
                            if ("cf".equals(receiveRecod.getScaleType())) {
                                bindScale("2");
                            } else if ("ce".equals(receiveRecod.getScaleType())) {
                                bindScale("1");
                            } else if ("ca".equals(receiveRecod.getScaleType())) {
                                bindScale("3");
                            } else {
                                bindScale("4");
                            }
                        }
                    }
                }
            }
        }
        if (i == 0 || i == 1) {
            Message msg1 = handler.obtainMessage(3);
            msg1.obj = receiveRecod;
            handler.sendMessage(msg1);
        }
        /*if (0 == i) {//旧秤
            receiveRecod = MyUtil.parseMessage(this.recordService, readMessage);
            String mac = (String) SPUtil.get(BaseBleActivity.this, "mac", "");
            LogUtil.d( "mac:" + mac);
            if (TextUtils.isEmpty(mac)) {
                LogUtil.d( "当前没有绑定mac");
                if ("cf".equals(receiveRecod.getScaleType())) {
                    bindScale("2");
                } else if ("ce".equals(receiveRecod.getScaleType())) {
                    bindScale("1");
                } else if ("ca".equals(receiveRecod.getScaleType())) {
                    bindScale("3");
                } else {
                    bindScale("4");
                }
                Message msg1 = handler.obtainMessage(3);
                msg1.obj = receiveRecod;
                handler.sendMessage(msg1);
            } else if (1 == i) {//阿里秤
                receiveRecod = MyUtil.parseZuKangMeaage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
                String mac = (String) SPUtil.get(BaseBleActivity.this, "mac", "");
                LogUtil.d( "mac:" + mac);
                if (TextUtils.isEmpty(mac)) {
                    LogUtil.d( "当前没有绑定mac");
                    if ("cf".equals(receiveRecod.getScaleType())) {
                        bindScale("2");
                    } else if ("ce".equals(receiveRecod.getScaleType())) {
                        bindScale("1");
                    } else if ("ca".equals(receiveRecod.getScaleType())) {
                        bindScale("3");
                    } else {
                        bindScale("4");
                    }
                }
                Message msg1 = handler.obtainMessage(3);
                msg1.obj = receiveRecod;
                handler.sendMessage(msg1);
            } else if (2 == i) {//新称过程数据
                LogUtil.i( readMessage);
            } else if (3 == i) {//新秤锁定数据
                LogUtil.i( "=======新秤锁定数据=======");
                receiveRecod = MyUtil.parseDLScaleMessage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
                if (null != receiveRecod) {
                    receiveRecod.setReceiveMsg(readMessage);
                    String mac = (String) SPUtil.get(BaseBleActivity.this, "mac", "");
                    LogUtil.d( "mac:" + mac);
                    if (TextUtils.isEmpty(mac)) {
                        LogUtil.d( "当前没有绑定mac");
                        if ("cf".equals(receiveRecod.getScaleType())) {
                            bindScale("2");
                        } else if ("ce".equals(receiveRecod.getScaleType())) {
                            bindScale("1");
                        } else if ("ca".equals(receiveRecod.getScaleType())) {
                            bindScale("3");
                        } else {
                            bindScale("4");
                        }
                    }
                }
                Message msg1 = handler.obtainMessage(0);
                msg1.obj = receiveRecod;
                handler.sendMessage(msg1);
            }
        }*/
    }

    /**
     * 自定义弹窗
     */
    public void openErrorDialog(String code) {
        try {
            Intent openDialog = new Intent(this, CustomDialogActivity.class);
            Bundle mBundle = new Bundle();
            mBundle.putString("error", code);
            openDialog.putExtras(mBundle);
            openDialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(openDialog);
        } catch (Exception e) {
        }
    }

    /**
     * 绑定MAC地址
     */
    private void bindScale(final String type) {
        LogUtil.d( "mac_address:" + mDeviceAddress);
        /***保存蓝牙数据实体类****/
       /* Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                *//***保存蓝牙数据实体类****//*
                DeviceMac deviceMac = realm.createObject(DeviceMac.class);
                deviceMac.setDeviceName(mDeviceName);
                deviceMac.setDeviceType(type);
                deviceMac.setMac(mDeviceAddress);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                LogUtil.e( "*********添加成功**********");
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                LogUtil.e( "*********添加失败**********");
            }
        });*/
        // SPUtil.put(BaseBleActivity.this, "mac_flag", 0);

        /*Map<String, String> map = new HashMap<>();
        map.put("deviceName", mDeviceName);
        map.put("mac", mDeviceAddress);
        map.put("deviceType", type);
        Gson gson = new Gson();
        String macJson = gson.toJson(map);
        SPUtil.put(BaseBleActivity.this, "mac", macJson);
        SPUtil.put(BaseBleActivity.this, "mac_flag", 0);
        String json = (String) SPUtil.get(BaseBleActivity.this, "mac", "");*/
    }

    private void saveData(Records receiveRecord) {
        AppData.hasCheckData = true;
        if (!BluetoolUtil.bleflag)
            TimeService.setIsdoing(true);
        if (null != receiveRecord && null != receiveRecord.getScaleType()) {
            float compare = 0;
            if (!TextUtils.isEmpty(receiveRecord.getCompareRecord()) && !"null".equals(receiveRecord.getCompareRecord())) {
                compare = Float.parseFloat(receiveRecord.getCompareRecord());
            }
            if (UtilConstants.KITCHEN_SCALE.equals(UtilConstants.CURRENT_SCALE)) {
                NutrientBo nutrient = null;
                if (!TextUtils.isEmpty(receiveRecord.getRphoto())) {
                    nutrient = CacheHelper.queryNutrientsByName(receiveRecord.getRphoto());
                }
                RecordDao.dueKitchenDate2(recordService, receiveRecord, nutrient);
            } else {
                RecordDao.handleData2(recordService, receiveRecord);
            }
            saveDataCallBack(receiveRecord);
            if (!BluetoolUtil.bleflag) {
                TimeService.setIsdoing(false);
            }
        }
    }

    /**
     * 保存后回调
     *
     * @param records
     */
    protected abstract void saveDataCallBack(Records records);

    /**
     * 是否为雷达界面
     *
     * @return
     */
    public boolean isAutoActivity() {
        String curActivityName = getRunningActivityName();
       LogUtil.w("***当前显示的activity名称是 curActivityName-->" + curActivityName);
        if (curActivityName.contains("AutoBLEActivity")) {
            return true;
        } else {
            return false;
        }
    }

    private String getRunningActivityName() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }

    private class Baby {
        public String headUrl;
        public String name;

        public String getHeadUrl() {
            return headUrl;
        }

        public void setHeadUrl(String headUrl) {
            this.headUrl = headUrl;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private class BabyGirdViewAdpter extends BaseAdapter {
        private LayoutInflater inflater;
        private List<Baby> list;

        public BabyGirdViewAdpter(LayoutInflater inflater, ArrayList<Baby> list) {
            this.inflater = inflater;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Baby baby = list.get(position);
            View view;
            ViewHolder viewHolder;
            if (convertView == null) {
                view = inflater.inflate(R.layout.selet_baby, null);
                viewHolder = new ViewHolder();
                viewHolder.image = (ImageView) view.findViewById(R.id.imageview);
                viewHolder.name = (TextView) view.findViewById(R.id.textview);
                view.setTag(viewHolder);
            } else {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }
//            viewHolder.image.setImageResource();
            viewHolder.image.setImageDrawable(getDrawable(R.drawable.baby));
            viewHolder.name.setText(baby.getName());
            return view;
        }

    }

    private class ViewHolder {
        ImageView image;
        TextView name;
    }

}


